import type { TimeBadgeProps } from './types'
import { Badge } from '../../components/badge'
import { TimerManager } from '../../lib/timer_manager'
import { getLiveTimeBadge } from './types'

export class TimeBadge {
  readonly id: string = 'time-badge'
  readonly name: string = 'TimeBadge'
  private readonly timerManager: TimerManager = TimerManager.getInstance()
  private readonly intervalId: string = 'time-badge-interval'
  private readonly startDate: Date

  private badge = new Badge({
    id: 'time-badge',
    ripple: true,
    type: 'dot',
    theme: 'green',
    position: 'before',
  })

  constructor(startDate: Date) {
    this.startDate = startDate
  }

  render(): string {
    const { badge, formattedTime } = getLiveTimeBadge(this.startDate)

    return `
      <div class="time-badge-container">
        <div class="time-badge" style="background: ${badge.bgColor}; color: ${badge.color}" data-level="${badge.level}">
          ${this.renderTimeBadge(badge)}
        </div>
        <div class="time-info">
          <div class="time-display">
            ${this.badge.render()}
            <span class="time-used">${formattedTime}</span>
          </div>
          ${badge.description ? `<p class="badge-desc">${badge.description}</p>` : ''}
        </div>
      </div>
    `
  }

  /**
   * 渲染时间徽章
   * @param badge 时间徽章属性
   * @returns 渲染后的 HTML 字符串
   */
  renderTimeBadge(badge: TimeBadgeProps): string {
    return `
      <span class="badge-icon">${badge.icon}</span>
      <span class="badge-name">${badge.name}</span>
    `
  }

  mount(container: JQuery<HTMLElement>): void {
    // 绑定徽章事件
    this.badge.mount(container)
    this.startAutoUpdate()
  }

  destroy(): void {
    this.stopAutoUpdate()
  }

  /**
   * 开始自动更新时间显示
   * @param interval 更新间隔，单位毫秒
   */
  startAutoUpdate(interval = 1000): void {
    this.stopAutoUpdate()

    this.timerManager.createTimerTask({
      id: this.intervalId,
      interval,
      callback: () => this.updateTimeDisplay(),
    })
  }

  /**
   * 停止自动更新时间显示
   */
  stopAutoUpdate(): void {
    this.timerManager.clearInterval(this.intervalId, true)
  }

  /**
   * 更新时间显示
   */
  private updateTimeDisplay(): void {
    const $container = $('.time-badge-container')

    if (!$container.length)
      return

    // 更新时间文本
    const { formattedTime, badge } = getLiveTimeBadge(this.startDate)
    const $timeElement = $container.find('.time-used')
    if ($timeElement.length) {
      $timeElement.text(formattedTime)
    }

    // 检查是否需要升级徽章
    const $currentBadgeElement = $container.find('.time-badge')
    if ($currentBadgeElement.length && $currentBadgeElement.attr('data-level') !== String(badge.level)) {
      this.handleLevelUp($container, badge)
    }
  }

  /**
   * 处理徽章升级
   * @param $container 包含徽章的容器元素
   * @param newBadge 新的徽章属性
   */
  private handleLevelUp($container: JQuery<HTMLElement>, newBadge: TimeBadgeProps): void {
    const $badgeElement = $container.find('.time-badge')
    if (!$badgeElement.length)
      return

    // 添加升级动画
    setTimeout(() => {
      $badgeElement.html(this.renderTimeBadge(newBadge))
      $badgeElement.attr('data-level', String(newBadge.level))
      $badgeElement.attr('style', `background: ${newBadge.bgColor}; color: ${newBadge.color}`)
    }, 500)
  }

  static styles(): string {
    return `
      .time-badge-container {
        position: absolute;
        top: 10px;
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 8px 12px;
        border-radius: 8px;
        transition: all 0.3s ease;
      }
      
      .time-badge {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        width: 60px;
        height: 60px;
        border-radius: 50%;
        font-size: 1.5em;
        box-shadow: 0 2px 8px rgba(0,0,0,0.1);
      }
      
      .badge-icon {
        display: flex;
        align-items: center;
        justify-content: center;
        
        img {
          filter: none !important;
        }
      }

      .badge-name {
        font-size: 10px;
        margin-top: 4px;
      }

      .time-info {
        display: flex;
        flex-direction: column;
        align-items: flex-start;
        justify-content: flex-start;
      }
      
      .time-display {
        display: flex;
        align-items: center;
        gap: 4px;
      }

      .time-used {
        font-size: 14px;
        font-weight: bold;
        color: #545454 !important;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }

      .badge-desc {
        margin: 4px 0 0 0;
        font-size: 12px;
        color: #666;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
        text-align: left;
      }
    `
  }
}
